package geyue.wechat.service;

import geyue.wechat.Constant;
import geyue.wechat.exception.WechatException;
import geyue.wechat.model.WechatContact;
import geyue.wechat.model.WechatMeta;
import geyue.wechat.robot.MoLiRobot;
import geyue.wechat.robot.Robot;
import geyue.wechat.robot.TuringRobot;
import geyue.wechat.util.Matchers;
import geyue.wechat.util.ReadFile;

import java.io.File;
import com.blade.kit.DateKit;
import com.blade.kit.FileKit;
import com.blade.kit.StringKit;
import com.blade.kit.http.HttpRequest;
import com.blade.kit.json.JSONArray;
import com.blade.kit.json.JSONKit;
import com.blade.kit.json.JSONObject;

public class WechatServiceImpl implements WechatService {

	// 茉莉机器人
	private Robot robot = new TuringRobot();

	/**
	 * 获取联系人
	 */
	@Override
	public WechatContact getContact(WechatMeta wechatMeta) {
		String url = wechatMeta.getBase_uri() + "/webwxgetcontact?pass_ticket="
				+ wechatMeta.getPass_ticket() + "&skey=" + wechatMeta.getSkey()
				+ "&r=" + DateKit.getCurrentUnixTime();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());

		HttpRequest request = HttpRequest.post(url)
				.contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		System.out.println(request.toString());

		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("获取联系人失败");
		}
		System.out.println(res);

		WechatContact wechatContact = new WechatContact();
		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			JSONObject BaseResponse = jsonObject.get("BaseResponse")
					.asJSONObject();
			if (null != BaseResponse) {
				int ret = BaseResponse.getInt("Ret", -1);
				if (ret == 0) {
					JSONArray memberList = jsonObject.get("MemberList")
							.asArray();
					JSONArray contactList = new JSONArray();

					if (null != memberList) {
						for (int i = 0, len = memberList.size(); i < len; i++) {
							JSONObject contact = memberList.get(i)
									.asJSONObject();
							// 公众号/服务号
							if (contact.getInt("VerifyFlag", 0) == 8) {
								continue;
							}
							// 特殊联系人
							if (Constant.FILTER_USERS.contains(contact
									.getString("UserName"))) {
								
								continue;
							}
							// 群聊
							if (contact.getString("UserName").indexOf("@@") != -1) {
								
								
								continue;
							}
							// 自己
							if (contact.getString("UserName").equals(
									wechatMeta.getUser().getString("UserName"))) {
								continue;
							}
							contactList.add(contact);
						}

						wechatContact.setContactList(contactList);
						wechatContact.setMemberList(memberList);

						this.getGroup(wechatMeta, wechatContact);

						return wechatContact;
					}
				}
			}
		} catch (Exception e) {
			throw new WechatException(e);
		}
		return null;
	}

	private void getGroup(WechatMeta wechatMeta, WechatContact wechatContact) {
		String url = wechatMeta.getBase_uri()
				+ "/webwxbatchgetcontact?type=ex&pass_ticket="
				+ wechatMeta.getPass_ticket() + "&skey=" + wechatMeta.getSkey()
				+ "&r=" + DateKit.getCurrentUnixTime();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());

		HttpRequest request = HttpRequest.post(url)
				.contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		System.out.println(request.toString());

		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("获取群信息失败");
		}
		System.out.println(res);

		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			JSONObject BaseResponse = jsonObject.get("BaseResponse")
					.asJSONObject();
			if (null != BaseResponse) {
				int ret = BaseResponse.getInt("Ret", -1);
				if (ret == 0) {
					JSONArray memberList = jsonObject.get("MemberList")
							.asArray();
					JSONArray contactList = new JSONArray();
					
					if (null != memberList) {
						for (int i = 0, len = memberList.size(); i < len; i++) {
							JSONObject contact = memberList.get(i)
									.asJSONObject();
							// 公众号/服务号
							if (contact.getInt("VerifyFlag", 0) == 8) {
								
								
								continue;
							}
							// 特殊联系人
							if (Constant.FILTER_USERS.contains(contact
									.getString("UserName"))) {
								
								
								continue;
							}
							// 群聊
							if (contact.getString("UserName").indexOf("@@") != -1) {
								
								
								continue;
							}
							// 自己
							if (contact.getString("UserName").equals(
									wechatMeta.getUser().getString("UserName"))) {
								
								
								continue;
							}
							contactList.add(contact);
						}

						wechatContact.setContactList(contactList);
						wechatContact.setMemberList(memberList);
					}
				}
			}
		} catch (Exception e) {
			throw new WechatException(e);
		}
	}

	/**
	 * 获取UUID
	 * appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi
	 * -bin%2Fmmwebwx-in%2Fwebwxnewloginpage&fun=new&lang=zh_CN"
	 */
	@Override
	public String getUUID() throws WechatException {
		// 获取报文头信息，得到报文信息，浏览器信息，ip地址，用户信息，用户什么都可以得到的
		HttpRequest request = HttpRequest.get(Constant.JS_LOGIN_URL, true,
				"appid", "wx782c26e4c19acffb", "fun", "new", "lang", "zh_CN",
				"_", DateKit.getCurrentUnixTime());

		System.out.println(request.toString());
		// ？
		String res = request.body();
		request.disconnect();

		if (StringKit.isNotBlank(res)) {
			String code = Matchers.match("window.QRLogin.code = (\\d+);", res);
			if (null != code) {
				if (code.equals("200")) {
					return Matchers.match("window.QRLogin.uuid = \"(.*)\";",
							res);
				} else {
					throw new WechatException("错误的状态码: " + code);
				}
			}
		}
		throw new WechatException("获取UUID失败");
	}

	/**
	 * 打开状态提醒
	 */
	@Override
	public void openStatusNotify(WechatMeta wechatMeta) throws WechatException {

		String url = wechatMeta.getBase_uri()
				+ "/webwxstatusnotify?lang=zh_CN&pass_ticket="
				+ wechatMeta.getPass_ticket();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());
		body.put("Code", 3);
		body.put("FromUserName", wechatMeta.getUser().getString("UserName"));
		body.put("ToUserName", wechatMeta.getUser().getString("UserName"));
		body.put("ClientMsgId", DateKit.getCurrentUnixTime());

		HttpRequest request = HttpRequest.post(url)
				.contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		System.out.println("" + request);

		String res = request.body();

		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("状态通知开启失败");
		}

		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			JSONObject BaseResponse = jsonObject.get("BaseResponse")
					.asJSONObject();
			if (null != BaseResponse) {
				int ret = BaseResponse.getInt("Ret", -1);
				if (ret != 0) {
					throw new WechatException("状态通知开启失败，ret：" + ret);
				}
			}
		} catch (Exception e) {
			throw new WechatException(e);
		}
	}

	/**
	 * 微信初始化
	 */
	@Override
	public void wxInit(WechatMeta wechatMeta) throws WechatException {
		String url = wechatMeta.getBase_uri() + "/webwxinit?r="
				+ DateKit.getCurrentUnixTime() + "&pass_ticket="
				+ wechatMeta.getPass_ticket() + "&skey=" + wechatMeta.getSkey();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", wechatMeta.getBaseRequest());

		HttpRequest request = HttpRequest.post(url)
				.contentType("application/json;charset=utf-8")
				.header("Cookie", wechatMeta.getCookie()).send(body.toString());
		System.out.println("" + request);

		// 有问题?

		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("微信初始化失败");
		}

		try {
			JSONObject jsonObject = JSONKit.parseObject(res);
			if (null != jsonObject) {
				JSONObject BaseResponse = jsonObject.get("BaseResponse")
						.asJSONObject();
				if (null != BaseResponse) {
					int ret = BaseResponse.getInt("Ret", -1);
					if (ret == 0) {
						wechatMeta.setSyncKey(jsonObject.get("SyncKey")
								.asJSONObject());
						wechatMeta.setUser(jsonObject.get("User")
								.asJSONObject());

						StringBuffer synckey = new StringBuffer();
						JSONArray list = wechatMeta.getSyncKey().get("List")
								.asArray();
						for (int i = 0, len = list.size(); i < len; i++) {
							JSONObject item = list.get(i).asJSONObject();
							synckey.append("|" + item.getInt("Key", 0) + "_"
									+ item.getInt("Val", 0));
						}
						wechatMeta.setSynckey(synckey.substring(1));
					}
				}
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 选择同步线路
	 */
	@Override
	public void choiceSyncLine(WechatMeta wechatMeta) throws WechatException {
		boolean enabled = false;

		for (String syncUrl : Constant.SYNC_HOST) {
			int[] res = this.syncCheck(syncUrl, wechatMeta);
			if (res[0] == 0) {
				String url = "https://" + syncUrl + "/cgi-bin/mmwebwx-bin";
				wechatMeta.setWebpush_url(url);
				System.out.println("选择线路：[{}]" + syncUrl);

				enabled = true;
				break;
			}
		}
		if (!enabled) {
			throw new WechatException("同步线路不通畅");
		}
	}

	/**
	 * 检测心跳
	 */
	@Override
	public int[] syncCheck(WechatMeta wechatMeta) throws WechatException {
		return this.syncCheck(null, wechatMeta);
	}

	/**
	 * 检测心跳
	 */
	private int[] syncCheck(String url, WechatMeta meta) throws WechatException {
		if (null == url) {
			url = meta.getWebpush_url() + "/synccheck";
		} else {
			url = "https://" + url + "/cgi-bin/mmwebwx-bin/synccheck";
		}

		JSONObject body = new JSONObject();
		body.put("BaseRequest", meta.getBaseRequest());

		HttpRequest request = HttpRequest.get(url, true, "r",
				DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5),
				"skey", meta.getSkey(), "uin", meta.getWxuin(), "sid",
				meta.getWxsid(), "deviceid", meta.getDeviceId(), "synckey",
				meta.getSynckey(), "_", System.currentTimeMillis()).header(
				"Cookie", meta.getCookie());
		System.out.println(request.toString());

		String res = request.body();
		request.disconnect();

		int[] arr = new int[] { -1, -1 };
		if (StringKit.isBlank(res)) {
			return arr;
		}

		String retcode = Matchers.match("retcode:\"(\\d+)\",", res);
		String selector = Matchers.match("selector:\"(\\d+)\"}", res);
		if (null != retcode && null != selector) {
			arr[0] = Integer.parseInt(retcode);
			arr[1] = Integer.parseInt(selector);
			return arr;
		}
		return arr;
	}

	/**
	 * @Description: 解析微信发来的请求（XML）
	 * @param @param request
	 * @date 2016 年 3 月 7 日 上午 10:04:02
	 */
	// public static Map<String, String> parseXml(HttpServletRequest request)
	// throws Exception {
	// // 将解析结果存储在 HashMap 中
	// Map<String, String> map = new HashMap<String, String>();
	// // 从 request 中取得输入流
	// InputStream inputStream = request.getInputStream();
	// // 读取输入流
	// SAXReader reader = new SAXReader();
	// Document document = reader.read(inputStream);
	// // 得到 xml 根元素
	// Element root = document.getRootElement();
	// // 得到根元素的所有子节点
	// List<Element> elementList = root.elements();
	// // 遍历所有子节点
	// for (Element e : elementList)
	// map.put(e.getName(), e.getText());
	// // 释放资源
	// inputStream.close();
	// inputStream = null;
	// return map;
	// }

	// public static String newsMessageToXml(NewsMessage newsMessage) {
	// xstream.alias("xml", newsMessage.getClass());
	// xstream.alias("item", new Article().getClass());
	// return xstream.toXML(newsMessage);
	// }
	//

	/**
	 * 处理消息
	 */
	@Override
	public void handleMsg(WechatMeta wechatMeta, JSONObject data) {

		if (null == data) {
			return;
		}

		JSONArray AddMsgList = data.get("AddMsgList").asArray();

		for (int i = 0, len = AddMsgList.size(); i < len; i++) {
			System.out.println("你有新的消息，请注意查收");

			JSONObject msg = AddMsgList.get(i).asJSONObject();

			int msgType = msg.getInt("MsgType", 0);

			// 获得发信息人的用户名
			String name = getUserRemarkName(msg.getString("FromUserName"));

			String content = msg.getString("Content");

			if (msgType == 10000) {
				String addMem=content.substring(content.indexOf("\"")+1, content.length()-6);
				String talk=ReadFile.readFileByLines("进群对话.txt");
				webwxsendmsg(wechatMeta, "@ "+addMem+" "+talk, msg.getString("FromUserName"));
				
			} else if (msgType == 51) {
				System.out.println("成功截获微信初始化消息");

			} else if (msgType == 1) {
				if (Constant.FILTER_USERS.contains(msg.getString("ToUserName"))) {
					continue;
				} else if (msg.getString("FromUserName").equals(
						wechatMeta.getUser().getString("UserName"))) {
					continue;
				} else if (msg.getString("ToUserName").indexOf("@@") != -1) {
					String[] peopleContent = content.split(":<br/>");
					// System.out.println("|" + name + "| " + peopleContent[0]
					// + ":\n" + peopleContent[1].replace("<br/>", "\n"));
				} else {
					// System.out.println(name + ": " + content);
					String ans = robot.talk(content);

					//webwxsendmsg(wechatMeta, ans, msg.getString("FromUserName"));
//					WeChatSendImg ws=new WeChatSendImg();
//					try {
//						ws.send("", wechatMeta, msg.getString("FromUserName"));
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//					String webwx_data_ticket = getDataTicket(wechatMeta
//							.getCookie());
//					SendFileUtilsTest5 sft = new SendFileUtilsTest5();
//					sft.upload(
//							"D:\\1.png",
//							wechatMeta.getWxuin(),
//							wechatMeta.getWxsid(),
//							wechatMeta.getSkey().substring(1,
//									wechatMeta.getSkey().length()), wechatMeta
//									.getDeviceId(), wechatMeta.getUser()
//									.getString("UserName"), msg
//									.getString("FromUserName"), System
//									.currentTimeMillis(), webwx_data_ticket,
//							wechatMeta.getPass_ticket());
					System.out.println("自动回复 " + ans);
				}
			} else if (msgType == 3) {

				String imgDir = Constant.config.get("app.img_path");
				String msgId = msg.getString("MsgId");

				FileKit.createDir(imgDir, false);

				String imgUrl = wechatMeta.getBase_uri()
						+ "/webwxgetmsgimg?MsgID=" + msgId + "&skey="
						+ wechatMeta.getSkey() + "&type=slave";
				// 获取信息
				// HttpRequest.get(imgUrl)
				// .header("Cookie", wechatMeta.getCookie())
				// .receive(new File(imgDir + "/" + msgId + ".jpg"));

//				HttpRequest.get(imgUrl)
//						.header("Cookie", wechatMeta.getCookie())
//						.receive(new File(imgDir + "/" + msgId + ".png"));
//				String ans1 = robot.talk(content);
//				webwxsendmsg(wechatMeta, ans1, msg.getString("FromUserName"));
				// webwxsendmsg(wechatMeta,
				// "二蛋还不支持图片呢",msg.getString("FromUserName"));

			} else if (msgType == 34) {
				webwxsendmsg(wechatMeta, "二蛋还不支持语音呢",
				msg.getString("FromUserName"));
			} else if (msgType == 37) {
				//好友请求
		        String url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxverifyuser?r=" 
						+ DateKit.getCurrentUnixTime()
						+ "&pass_ticket=" 
						+wechatMeta.getPass_ticket();
		        JSONObject body = new JSONObject();
				JSONObject baseRequest = new JSONObject();
				
				baseRequest.put("Uin",Long.parseLong(wechatMeta.getWxuin()));
				baseRequest.put("Sid", wechatMeta.getWxsid());
				baseRequest.put("Skey", wechatMeta.getSkey());
				baseRequest.put("DeviceID", wechatMeta.getDeviceId());
				body.put("BaseRequest", baseRequest);
				body.put("Opcode", 3);
				body.put("VerifyUserListSize", 1);
				body.put("VerifyContent", "");
				body.put("SceneListCount", 1);
				body.put("skey", wechatMeta.getSkey());
				
				JSONArray verifyUserListv = new JSONArray();
				verifyUserListv.add(33);
				body.put("SceneList", verifyUserListv);
				
				JSONArray verifyUserList = new JSONArray();		
				JSONObject verifyUserList1 = new JSONObject();
				
				System.out.println(msg.get("RecommendInfo")+"++++++++");
				JSONObject recommendInfo= msg.get("RecommendInfo").asJSONObject();
				
				verifyUserList1.put("Value", recommendInfo.getString("UserName"));
				verifyUserList1.put("VerifyUserTicket", recommendInfo.getString("Ticket"));

				verifyUserList.add(verifyUserList1);
				body.put("VerifyUserList", verifyUserList);
				System.out.println("body"+body.toString());
				HttpRequest request = HttpRequest.post(url)
						.contentType("application/json;charset=utf-8")
						.header("Cookie", wechatMeta.getCookie()).send(body.toString());
				System.out.println( request);

				String res = request.body();

				request.disconnect();
				System.out.println("res++++++++++++++++++++++++"+res);
				
			} else if (msgType == 42) {
				 System.out.println(name + " 给你发送了一张名片:");
				 System.out.println("=========================");

			}
		}
	}

	private String getDataTicket(String cookie) {
		String res = "";
		String[] cookies = cookie.split(";");
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].contains("webwx_data_ticket")) {
				res = cookies[i].replace("webwx_data_ticket=", "")
						.replace(";", "").trim();
				System.out.println("webwx_data_ticket=*****" + res);
			}
		}
		return res;
	}

	/**
	 * 发送文字消息
	 */
	private void webwxsendmsg(WechatMeta meta, String content, String to) {
		String url = meta.getBase_uri()
				+ "/webwxsendmsg?lang=zh_CN&pass_ticket="
				+ meta.getPass_ticket();

		JSONObject body = new JSONObject();

		String clientMsgId = DateKit.getCurrentUnixTime()
				+ StringKit.getRandomNumber(5);

		JSONObject Msg = new JSONObject();
		Msg.put("Type", 1);
		Msg.put("Content", content);
		Msg.put("FromUserName", meta.getUser().getString("UserName"));
		Msg.put("ToUserName", to);
		Msg.put("LocalID", clientMsgId);
		Msg.put("ClientMsgId", clientMsgId);

		body.put("BaseRequest", meta.getBaseRequest());
		body.put("Msg", Msg);

		HttpRequest request = HttpRequest.post(url)
				.contentType("application/json;charset=utf-8")
				.header("Cookie", meta.getCookie()).send(body.toString());
		System.out.println("发送消息...");
		System.out.println("" + request);

		request.body();
		request.disconnect();
	}

	private String getUserRemarkName(String id) {
		String name = "这个人物名字未知";
		for (int i = 0, len = Constant.CONTACT.getMemberList().size(); i < len; i++) {
			JSONObject member = Constant.CONTACT.getMemberList().get(i)
					.asJSONObject();
			if (member.getString("UserName").equals(id)) {
				if (StringKit.isNotBlank(member.getString("RemarkName"))) {
					name = member.getString("RemarkName");
				} else {
					name = member.getString("NickName");
				}
				return name;
			}
		}
		return name;
	}

	@Override
	public JSONObject webwxsync(WechatMeta meta) throws WechatException {

		String url = meta.getBase_uri() + "/webwxsync?skey=" + meta.getSkey()
				+ "&sid=" + meta.getWxsid();

		JSONObject body = new JSONObject();
		body.put("BaseRequest", meta.getBaseRequest());
		body.put("SyncKey", meta.getSyncKey());
		body.put("rr", DateKit.getCurrentUnixTime());

		HttpRequest request = HttpRequest.post(url)
				.contentType("application/json;charset=utf-8")
				.header("Cookie", meta.getCookie()).send(body.toString());
		System.out.println(request.toString());

		String res = request.body();
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("同步syncKey失败");
		}

		JSONObject jsonObject = JSONKit.parseObject(res);
		JSONObject BaseResponse = jsonObject.get("BaseResponse").asJSONObject();
		if (null != BaseResponse) {
			int ret = BaseResponse.getInt("Ret", -1);
			if (ret == 0) {
				meta.setSyncKey(jsonObject.get("SyncKey").asJSONObject());
				StringBuffer synckey = new StringBuffer();
				JSONArray list = meta.getSyncKey().get("List").asArray();
				for (int i = 0, len = list.size(); i < len; i++) {
					JSONObject item = list.get(i).asJSONObject();
					synckey.append("|" + item.getInt("Key", 0) + "_"
							+ item.getInt("Val", 0));
				}
				meta.setSynckey(synckey.substring(1));
				return jsonObject;
			}
		}
		return null;
	}

}
